
<template>
  <div class="repair-center-wrapper">
    <!-- 公告部分 -->
    <el-collapse v-model="historyAnnouncement" class="announcement-section">
      <el-collapse-item name="1">
        <template #title>
          <div class="announcement-header">
            <i class="fa fa-bullhorn" aria-hidden="true"></i>&nbsp;系统公告
          </div>
        </template>
        <el-alert v-for="item in pageAnnouncementList" :key="item.id" :title="item.title"
          :type="item.alertType || 'info'" :closable="false" class="announcement-item">
          <div class="layout">
            <div class="content">{{ item.content }}</div>
            <div class="about">
              <div class="issueAuthor">
                <i class="fa fa-user-circle-o"></i>&nbsp;{{ item.issueAuthor }}
              </div>
              <div class="issueTime">
                <span><i class="fa fa-clock-o"
                    aria-hidden="true"></i>&nbsp;{{ item.issueTime }}</span>
              </div>
            </div>
          </div>
        </el-alert>
        <div class="pagination">
          <el-pagination @size-change="val => pagination.pageSize = val"
            @current-change="val => pagination.currentPage = val"
            :current-page="pagination.currentPage" :pager-count="pagination.pagerCount"
            :page-sizes="pagination.pageSizes" :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" background>
          </el-pagination>
        </div>
      </el-collapse-item>
    </el-collapse>
    
    <!-- 报修表单部分 -->
    <div class='repairCenter_container'>
      <el-card class="repair-form-card">
        <template #header>
          <div class="card-header">
            <span class="title">申请报修</span>
            <el-button type="primary" @click="onSubmit" class="submit-btn">提交申请</el-button>
          </div>
        </template>

        <el-form :model="orderForm" :rules="rules" status-icon label-width="8rem"
          ref="ruleForm" class="repair-form">
          <el-form-item label="联系地址" prop="repairAddress">
            <el-input v-model="orderForm.repairAddress" clearable placeholder="请输入您的详细地址"></el-input>
          </el-form-item>

          <el-form-item label="手机号码" prop="repairPhone">
            <el-input v-model="orderForm.repairPhone" clearable maxlength="11" minlength="11" placeholder="请输入您的联系电话">
            </el-input>
          </el-form-item>

          <el-form-item label="报修类型" prop="typeMark" class="repair-type-section">
            <div class="repair-type-container">
              <el-badge value="hot" class="repair-type-item" v-for="item in repairType"
                :key="item.mark" :hidden="!item.typeHot">
                <el-tag class="type-tag" @click="tagEvent(item)" :type="item.tagType" :effect="item.tagType === 'danger' ? 'dark' : 'light'">
                  {{item.typeValue}}
                </el-tag>
              </el-badge>
            </div>
          </el-form-item>

          <el-form-item label="报修问题" prop="repairContent">
            <el-input type="textarea" clearable v-model="orderForm.repairContent" show-word-limit
              rows="4" placeholder="请详细描述您遇到的问题，以便我们更好地为您服务">
            </el-input>
          </el-form-item>

          <el-form-item label="图片资料" class="upload-section">
            <el-upload class="image-uploader" :action="action" list-type="picture-card" ref="upload"
              multiple :auto-upload="false" :http-request="uploadFile"
              accept=".jpg,.jpeg,.png,.JPG,.JPEG" :on-preview="handlePictureCardPreview"
              :on-remove="(file, fileList)=>{return handleRemove(file, fileList)}" :limit="3"
              :on-exceed="onExceed"
              :on-success="(response, file, fileList)=>{return onSuccess(response, file, fileList)}">
              <div class="upload-trigger">
                <i class="fa fa-plus" aria-hidden="true"></i>
                <div class="upload-text">点击上传</div>
              </div>
            </el-upload>
            <div class="upload-tip">最多上传3张图片，支持JPG、PNG格式</div>
            <el-dialog v-model="dialogVisible" class="preview-dialog">
              <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
export default {
  data () {
    //这里存放数据
    return {
      historyAnnouncement: '1',
      announcementList: [],
      pagination: {
        pageSize: 3,
        pageSizes: [3, 10, 100, 200],
        pagerCount: 5,
        currentPage: 1,
        total: 0
      },
      repairType: [],
      orderForm: {
        typeMark: '',
        repairAddress: '3423',
        repairContent: '厕所喷屎',
        repairPhone: '15281056531'
      },
      rules: {
        typeMark: [
          { required: true, message: '请选择报修类型', trigger: 'change' },
        ],
        repairAddress: [
          { required: true, message: '请输入联系地址', trigger: 'blur' },
        ],
        repairPhone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        repairContent: [
          { required: true, message: '请输入报修问题', trigger: 'blur' },
        ]
      },
      action: this.axios.defaults.baseURL + "/userHome/photo",
      formData: '',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false
    }
  },
  //监听属性 类似于data概念
  computed: {
    'pageAnnouncementList': function () {
      return this.announcementList.slice(
        (this.pagination.currentPage - 1) * this.pagination.pageSize, this.pagination.currentPage * this.pagination.pageSize
      )
    },
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    /**
     * @description: 后端拉取所有公告信息
     * @param {*}
     * @return {*}
     */
    async execPullAllAnnouncement () {
      try {
        console.log("开始获取公告信息");
        // 确保API路径正确，不添加多余前缀
        const result = await (await this.axios.get('/userHome/pullAllAnnouncement')).data
        console.log("公告信息响应:", result);
        
        if (result.code === 43000) {
          this.announcementList = result.data || []
          this.announcementList.sort(function (a, b) {
            return b.issueTime < a.issueTime ? -1 : 1
          })
          this.pagination.total = this.announcementList.length
        } else if (result.code === 43001) {
          this.announcementList = [];
          this.pagination.total = 0;
          ElMessage.warning(result.msg || "暂无公告")
        }
      } catch (error) {
        console.error("获取公告失败:", error);
        // 失败时使用空数组
        this.announcementList = [];
        this.pagination.total = 0;
        // 显示友好的错误信息
        ElMessage.warning("获取公告信息失败，请稍后再试");
      }
    },
    tagEvent (item) {
      if (item.tagType == 'info') {
        //此处修改选中报修类型样式
        item.tagType = 'danger';
        this.orderForm.typeMark = item.typeMark;
      } else {
        item.tagType = 'info';
        this.orderForm.typeMark = '';
      }
      this.repairType.forEach((it, index) => {
        if (item.typeMark != it.typeMark) {
          it['tagType'] = 'info'
        }
      })
      this.$forceUpdate();
    },
    getRepairType () {
      // 修改：确保能正确获取报修类型数据
      console.log("开始获取报修类型数据");
      this.axios.get("/userHome/repairType").then(res => {
        if (res.data && res.data.code == 43000 && res.data.data) {
          console.log("获取到报修类型数据:", res.data.data);
          this.repairType = res.data.data;
          // 同时更新store中的数据
          if (window.useMainStore) {
            const store = window.useMainStore();
            store.repairType = res.data.data;
          }
          this.repairType.forEach((item, index) => {
            item['tagType'] = 'info'
          })
        } else {
          console.error("报修类型数据获取失败或为空");
        }
      }).catch(err => {
        console.error("获取报修类型数据出错:", err);
      });
    },
    /**
     * userHome/createOrder
     * orderForm:{"repairAddress":"3303","repairPhone":"17345252917","typeMark":1}
     * @description: 文件超出个数限制时的钩子
     * @param {*} files
     * @param {*} fileList
     * @return {*}
     * @author: 小花
     */
    onExceed (files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    /**
     * @description: 手动文件上传
     * @param {*}
     * @return {*}
     * @author: 小花
     */
    submitUpload () {
      this.formData = new FormData();
      this.formData.append('orderForm', JSON.stringify(this.orderForm));
      this.$refs.upload.submit();

      let i = this.formData.entries();
      if (i.next().done) return;

      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          'satoken': localStorage.getItem("satoken")
        }
      }
      this.axios.post("/userHome/createOrder", this.formData, config).then(res => {
        if (res.data.code == 43000) {
          this.$message.success("申请报修成功");
          this.$refs.upload.clearFiles();
          this.orderForm = {};
        }

      }).catch(res => {
        console.log(res)
      })
    },
    uploadFile (file) {
      this.formData.append('file', file.file);
    },
    /**
     * @description: 上传成功返回列表显示
     * @param {*} response
     * @param {*} file
     * @param {*} fileList
     * @param {*} idx
     * @return {*}
     * @author: 小花
     */
    onSuccess (response, file, fileList, idx) {
      // 这里是element的上传地址，对应的name,url,自己打印fileList对照
      this.formList.push({ name: file.name, url: file.url });
    },
    /**
     * @description: 移除图片
     * @param {*} file
     * @param {*} fileList
     * @param {*} idx
     * @return {*}
     * @author: 小花
     */
    handleRemove (file, fileList) { },
    /**
     * @description: 图片放大
     * @param {*} file
     * @return {*}
     * @author: 小花
     */
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /**
     * @description: 提交申请报修
     * @param {*}
     * @return {*}
     * @author: 小花
     */
    onSubmit () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.submitUpload();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getRepairType();
    this.execPullAllAnnouncement();
    
    // 添加：初始化状态数据到全局store
    if (window.useMainStore) {
      const store = window.useMainStore();
      if (!store.repairStatus || store.repairStatus.length === 0) {
        console.log("初始化报修状态数据");
        
        // 设置静态报修状态数据
        store.repairStatus = [
          { statusCode: 1, statusValue: "待接单" },
          { statusCode: 2, statusValue: "已接单" },
          { statusCode: 3, statusValue: "维修中" },
          { statusCode: 4, statusValue: "维修完成" },
          { statusCode: 5, statusValue: "已拒绝" }
        ];
        
        // 同时从API获取
        this.axios.get("/userHome/repairStatus").then(res => {
          console.log("报修状态API响应:", res);
          if (res.data && res.data.code === 43000 && res.data.data) {
            store.repairStatus = res.data.data;
          }
        }).catch(err => {
          console.error("获取报修状态数据错误:", err);
        });
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.repair-center-wrapper {
  width: 100%;
  padding: 5px;
  max-height: calc(100vh - 80px);
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  
  // 公告部分样式
  .announcement-section {
    margin-bottom: 15px;
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
    border: 1px solid rgba(255, 255, 255, 0.6);
    
    .announcement-header {
      font-size: 15px;
      font-weight: 600;
      display: flex;
      align-items: center;
      color: #2c3e50;
      letter-spacing: 0.3px;
      
      i {
        color: #f39c12;
        font-size: 16px;
        margin-right: 6px;
      }
    }
    
    .announcement-item {
      margin-bottom: 10px;
      transition: all 0.3s;
      border-radius: 8px;
      overflow: hidden;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 15px rgba(0, 0, 0, 0.05);
      }
      
      :deep(.el-alert__content) {
        width: 100%;
        padding: 8px;
        
        .layout {
          .content {
            margin-bottom: 6px;
            font-size: 13px;
            line-height: 1.5;
          }
          
          .about {
            display: flex;
            justify-content: space-between;
            font-size: 11px;
            color: #606266;
            
            .issueAuthor, .issueTime {
              display: flex;
              align-items: center;
              
              i {
                margin-right: 4px;
              }
            }
          }
        }
      }
    }
  }
  
  // 报修表单部分样式
  .repairCenter_container {
    .repair-form-card {
      border-radius: 12px;
      overflow: hidden;
      transition: all 0.3s;
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.07);
      border: 1px solid rgba(255, 255, 255, 0.8);
      
      &:hover {
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
      }
      
      :deep(.el-card__header) {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        padding: 12px 15px;
        border-bottom: none;
      }
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .title {
          color: #fff;
          font-size: 16px;
          font-weight: 600;
          letter-spacing: 0.5px;
          text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
        
        .submit-btn {
          border-radius: 20px;
          font-weight: 600;
          padding: 6px 15px;
          background: #fff;
          color: #4facfe;
          border: none;
          box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
          transition: all 0.3s;
          font-size: 13px;
          
          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
            background: #f8f9fa;
          }
          
          &:active {
            transform: translateY(0);
          }
        }
      }
      
      .repair-form {
        padding: 15px 15px 5px;
        
        :deep(.el-form-item) {
          margin-bottom: 15px;
          
          .el-form-item__label {
            font-weight: 500;
            color: #2c3e50;
            padding: 0 12px 0 0;
            font-size: 13px;
          }
          
          .el-input__wrapper, .el-textarea__wrapper {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03), 0 0 0 1px rgba(0, 0, 0, 0.05) inset;
            border-radius: 8px;
            transition: all 0.3s;
            
            &:hover {
              box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.08) inset;
            }
            
            &.is-focus {
              box-shadow: 0 2px 12px rgba(79, 172, 254, 0.1), 0 0 0 1px #4facfe inset;
            }
          }
        }
        
        .repair-type-section {
          .repair-type-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            
            .repair-type-item {
              margin: 0;
              
              .type-tag {
                padding: 6px 12px;
                cursor: pointer;
                border-radius: 20px;
                font-size: 12px;
                font-weight: 500;
                transition: all 0.3s;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
                
                &:hover {
                  transform: translateY(-2px);
                  box-shadow: 0 5px 12px rgba(0, 0, 0, 0.1);
                }
              }
            }
          }
        }
        
        .upload-section {
          .image-uploader {
            :deep(.el-upload--picture-card) {
              border-radius: 8px;
              transition: all 0.3s;
              border: 2px dashed #d9d9d9;
              width: 100px;
              height: 100px;
              
              &:hover {
                border-color: #4facfe;
                transform: translateY(-2px);
              }
            }
            
            .upload-trigger {
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
              height: 100%;
              
              i {
                font-size: 20px;
                color: #8c939d;
                margin-bottom: 6px;
                transition: all 0.3s;
              }
              
              .upload-text {
                color: #8c939d;
                font-size: 12px;
                transition: all 0.3s;
              }
              
              &:hover {
                i, .upload-text {
                  color: #4facfe;
                }
              }
            }
          }
          
          .upload-tip {
            margin-top: 6px;
            font-size: 11px;
            color: #606266;
          }
        }
      }
    }
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    padding: 8px 0;
    position: sticky;
    bottom: 0;
    z-index: 10;
    background-color: #fff;
    
    :deep(.el-pagination) {
      padding: 0;
      font-size: 12px;
      
      .btn-prev, .btn-next {
        border-radius: 8px;
        background: #fff;
        border: 1px solid #e2e8f0;
        transition: all 0.3s;
        min-width: 28px;
        height: 28px;
        line-height: 28px;
        
        &:hover {
          color: #fff;
          background: #4facfe;
          border-color: #4facfe;
          transform: translateY(-2px);
          box-shadow: 0 3px 10px rgba(79, 172, 254, 0.3);
        }
      }
      
      .el-pager {
        li {
          border-radius: 8px;
          font-weight: 500;
          border: 1px solid #e2e8f0;
          margin: 0 2px;
          transition: all 0.3s;
          min-width: 28px;
          height: 28px;
          line-height: 28px;
          
          &:not(.active):hover {
            transform: translateY(-2px);
            box-shadow: 0 3px 10px rgba(79, 172, 254, 0.2);
            border-color: #4facfe;
            color: #4facfe;
          }
          
          &.active {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            transform: scale(1.1);
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.3);
          }
        }
      }
    }
  }
}

/* 媒体查询适配移动设备 */
@media screen and (max-width: 768px) {
  .repair-center-wrapper {
    padding: 3px;
    max-height: calc(100vh - 60px);
    
    .announcement-section {
      margin-bottom: 10px;
    }
    
    .repairCenter_container {
      .repair-form-card {
        .repair-form {
          padding: 10px 8px 5px;
        }
        
        :deep(.el-card__header) {
          padding: 10px;
        }
        
        .card-header {
          .title {
            font-size: 14px;
          }
          
          .submit-btn {
            padding: 5px 12px;
            font-size: 12px;
          }
        }
      }
      
      .repair-type-section {
        .repair-type-container {
          gap: 6px;
          
          .repair-type-item {
            .type-tag {
              padding: 5px 10px;
              font-size: 11px;
            }
          }
        }
      }
      
      .upload-section {
        .image-uploader {
          :deep(.el-upload--picture-card) {
            width: 80px;
            height: 80px;
          }
        }
      }
    }
    
    .pagination {
      padding: 5px 0;
      
      :deep(.el-pagination) {
        .el-pagination__sizes {
          display: none;
        }
      }
    }
  }
}
</style>